import { Toast } from 'antd-mobile';
import { reqRegister } from "../../http/api";

// 1.初始值
const initState = {
    // 1.1 初始化
    user: {
        phone: "",
        nickname: "",
        password: ""
    }
}

// types
const types = {
    // 1.2 
    REGISTER_CHANGE_USER: "REGISTER_CHANGE_USER"
}
// reducer
export const registerReducer = (state = initState, action) => {
    switch (action.type) {
        // 1.3 
        case types.REGISTER_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
            break;
        default:
            return state
    }
}
// actions
export const actions = {
    // /1.4
    changeUser: (key, value) => ({ type: types.REGISTER_CHANGE_USER, key, value }),
    // 1.6注册逻辑
    reqRegisterAction:(push)=>{
        // console.log(state);
        return (dispatch,getState)=>{
            //1.7 取出存在register自己仓库中的user  l
            let {user} = getState().register
            // 1.8 发请求
            reqRegister(user).then(res=>{
                if(res.data.code === 200){
                    // 弹成功
                    Toast.success(res.data.msg)
                    // 跳转到登录页面
                    push('/login')
                }
            })
        }
    }

}


// 导出数据
// 1.5
export const getUser = state => state.register.user